const connection = require('../app/databases');

class UserService {
  async getUserByName(name) {
    try {
      const statement = `SELECT * FROM user WHERE name = ?`;
      const [result] = await connection.execute(statement, [name]);

      return result;
    } catch (error) {
      return error.message;
    }
  }

  async addUser(name, password) {
    try {
      const statement = `INSERT INTO user (name, password) VALUES (?, ?) `;
      const [result] = await connection.execute(statement, [name, password]);
      
      return result;
    } catch (error) {
      return error.message;
    }
  }

  async isPermission(tableName, resourceId, userId) {
    try {
      const statement = `SELECT * FROM ${tableName} WHERE id = ? AND user_id = ?;`;
      const [result] = await connection.execute(statement, [resourceId, userId]);

      return result.length === 0 ? false : true;
    } catch (error) {
      return error.message;
    }
  }

  async getAvatarById(userId) { 
    try {
      const statement = `SELECT * FROM avatar WHERE user_id = ?;`;
      const [result] = await connection.execute(statement, [userId]);

      return result[0];
    } catch (error) {
      return error.message;
    }
  }

  async removeUserById(userId) { 
    try {
      // 获取用户本地头像文件名称
      const statement1 = `SELECT filename FROM avatar WHERE user_id = ?;`;
      const [result1] = await connection.execute(statement1, [userId]);
      // 删除用户
      const statement2 = `DELETE FROM user WHERE id = ?;`;
      const [result2] = await connection.execute(statement2, [userId]);
      
      return result1[0];
    } catch (error) {
      return error.message;
    }
  }
}

module.exports = new UserService();